package views.components;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import utils.ReflectionUtils;
import utils.ViewComponentUtils;
import app.structure.Arg;
import com.vaadin.ui.AbstractField;
import com.vaadin.ui.CustomComponent;
import com.vaadin.ui.GridLayout;
import com.vaadin.ui.Notification;
import com.vaadin.ui.Notification.Type;

@SuppressWarnings("serial")
public class ArgPanel extends CustomComponent {
	/**
	 * vector de components generics
	 */
	private List<AbstractField<?>> components;
	private HashMap<String, Arg> hashArgs;
	private GridLayout gridLayout;

	public HashMap<String, Arg> getHashArgs() {
		return hashArgs;
	}

	public List<AbstractField<?>> getComponents() {
		return components;
	}

	public ArgPanel(Class<?> myClass, String viewName)
			throws ClassNotFoundException {

		components = new ArrayList<AbstractField<?>>();
		// a partir de la clase agafem els args

		hashArgs = ReflectionUtils.getArgsAnnotationsView(myClass,viewName);

		// fem que es vetja en columnes de tres

		int width = 3;
		int height = hashArgs.size() / width;
		int resto = hashArgs.size() % width;

		if (resto > 0) {
			++height;
		}

		gridLayout = new GridLayout(width, height);

		AbstractField<?> component;

		for (Arg arg : hashArgs.values()) {

			try {
				component = ViewComponentUtils.createComponent(arg);
				components.add(component);
				gridLayout.addComponent(component);
			} catch (Exception e) {
				Notification.show(e.getMessage(), Type.ERROR_MESSAGE);
				e.printStackTrace();
			}

		}

		setCompositionRoot(gridLayout);
	}
}
